import React, { Component } from 'react'
import { connect } from "react-redux";
import { deepFullCopy, messages, queryCurrencyPrecision } from "share/common";
import moment from "moment";
import { Checkbox, Popover, Tag, Button, message, Alert } from "antd";
import constants from "share/constants";
import selectorData from "share/selectorData";
import CostCenterSearchForm from "components/template/cost-center-search-form/cost-center-search-form";
import borrowService from "../../loan-billing/borrow-and-return.service";
import AdvancedTable from "components/advanced-table";
import financeViewService from "./finance-view.service";
import openSlideFrame from "share/openSlideFrame";
import ExportModal from "components/template/export-modal/export-modal";
import Partner from "containers/pay/template/partner"
import errorMessage from "share/errorMessage";
import Department from "components/template/department";
import SelectBatchNumber from "../expense-view/select-batch-number";

@connect(mapStateToProps)
class LoanView extends Component {

  statusOptions = [
    { label: messages('finance-1.key493')/*审批中*/, value: 'submitted' },
    { label: messages('finance-1.key494')/*已通过*/, value: 'approval_pass' },
    { label: messages('finance-1.key238')/*已驳回*/, value: 'approval_reject' },
    { label: messages('finance-1.key495')/*审核通过*/, value: 'audit_pass' },
    { label: messages('finance-1.key496')/*审核驳回*/, value: 'audit_reject' },
    { label: messages('finance-1.key497')/*付款中*/, value: 'payment_in_process' },
    { label: messages('finance-1.key471')/*已付款*/, value: 'finance_loan' },
    { label: messages('finance-1.key13')/*还款中*/, value: 'paid_in_process' },
    { label: messages('finance-1.key14')/*已还款*/, value: 'paid_finish' }
  ];

  columns = [
    { title: messages('common.user.id')/*工号*/, dataIndex: 'employeeID' },
    { title: messages('common.applicant')/*申请人*/, dataIndex: 'applicant' },
    {
      title: messages('common.submit.date')/*提交日期*/,
      dataIndex: 'lastSubmittedDate', width: 120, sorter: true,
      render: (date, record) =>
        date ? moment(date).format('YYYY-MM-DD') : moment(record.createDate).format('YYYY-MM-DD')
    },
    {
      title: messages('finance-1.key498')/*单据类型*/, sorter: true,
      dataIndex: 'formName', render: value => <Popover content={value}>{value}</Popover>
    },
    {
      title: messages('common.document.code')/*单号*/, dataIndex: 'businessCode', render: (value, record) => (
        <Popover content={record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}>
          {record.parentBusinessCode ? `${record.parentBusinessCode} - ${value}` : value}
        </Popover>
      ), sorter: true
    },
    { title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 72 },
    {
      title: messages('finance-1.key87')/*事由说明temp*/, dataIndex: 'title',
      render: value => <Popover content={value}>{value}</Popover>
    },
    {
      title: messages('finance-1.key16')/*借款金额*/, sorter: true,
      dataIndex: 'totalAmount', render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
    },
    {
      title: messages('finance-1.key499')/*凭证编号*/, dataIndex: 'origDocumentSequence',
      render: value => <Popover content={value} placement="topLeft">{value}</Popover>
    },
    {
      title: messages('finance-1.key500')/*批量打印批次号*/, dataIndex: 'loanBillBatchId',
      render: value => value ? <Popover content={value} placement="topLeft">{value}</Popover> : '-'
    },
    {
      title: messages('common.column.status')/*状态*/, dataIndex: 'status',
      render: (value, record) => {
        let applicationType = +record.entityType === 1008 ? 2005 : '';
        let text = constants.getTextByValue(String(value + '' + applicationType), 'documentStatus') ||
          constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') ||
          constants.getTextByValue(String(value), 'documentStatus');
        let color = constants.getTextByValue(String(value + '' + applicationType), 'documentStatus', 'color') ||
          constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'color') ||
          constants.getTextByValue(String(value), 'documentStatus', 'color');
        return <Tag color={color}>{text}</Tag>
      }
    },
    {
      title: messages('common.operation')/*操作*/,
      dataIndex: 'operation',
      render: (value, record) =>
        <a onClick={event => this.print(record, event)}>{messages('common.print')/*打印*/}</a>
    },
    {
      title: messages('finance-1.key34')/*快递单号*/, dataIndex: 'deliveryCode', hide: true,
      render: value => value ? <Popover content={value} placement="topLeft">{value}</Popover> : '-'
    }
  ];

  state = {
    sort: '',
    searchParams: {},
    batchBtnLoading: false
  };

  print = (record, event) => {
    event.stopPropagation();
    borrowService.printLoanApplication(record.entityOID).then(res => {
      window.open(res.data.link, '_blank')
    })
  };

  handleSortChange = (pagination, filter, sorter) => {
    let sort = '';
    if (sorter.order) {
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`;
    }
    this.setState({ sort }, this.advancedTableRef.getList);
  };


  searchForm = [
    {
      id: 'formOIDs', component: 'AllSelector', label: messages('finance-1.key501')/*表单类型*/,
      props: {
        type: 'authority_form',
        params: { formType: 3001 },
        labelKey: 'formName'
      },
      parser: value => ({
        formOIDs: value ? value.map(item => item.formOID) : null
      }),
      dataIndex: 'formName'
    },
    {
      id: 'userOID', label: messages('finance-1.key90')/*申请人姓名/工号*/, component: 'Selector',
      props: {
        placeholder: messages('common.please.input')/*请输入*/ + messages('finance-1.key90')/*申请人姓名/工号*/,
        selectorItem: {
          ...selectorData['user'],
          url: `/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
          label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
              (`（${record.status === 1002 ?
                  messages('finance-1.key91')/*待离职员工*/ :
                  messages('finance-1.key92')/*离职员工*/}）`
              ) :
              ''
          )}`)
        }
      },
      dataIndex: 'applicant'
    },
    {
      id: 'businessCode', component: 'Selector', label: messages('finance-1.key502')/*单据ID*/,
      props: {
        placeholder: messages('common.please.input')/*请输入*/ + messages('finance-1.key502')/*单据ID*/,
        type: 'business_code_borrow'
      },
      dataIndex: 'businessCode'
    },
    {
      id: 'departmentOIDs', label: messages('common.department')/*部门*/, component: <Department/>,
      parser: value => ({ departmentOIDs: value ? value.map(item => item.departmentOID) : undefined }),
      tagParser: value => (value.map(item => item.title).join(','))
    },
    {
      id: 'submittedDate', label: messages('common.submit.date')/*提交日期*/, component: 'DateRangePicker',
      initialValue: [moment().subtract(1, 'month'), moment()],
      parser: value => ({
        beginDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
        endDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
      }),
      dataIndex: 'lastSubmittedDate'
    },
    {
      id: 'approvalDate', label: messages('finance-1.key503')/*审批日期*/, component: 'DateRangePicker',
      parser: value => ({
        approvalStartDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
        approvalEndDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
      })
    },
    {
      id: 'auditedApprovalDate', label: messages('finance-1.key504')/*审核日期*/, component: 'DateRangePicker',
      parser: value => ({
        auditedApprovalStartDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
        auditedApprovalEndDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
      })
    },
    {
      id: 'currencyCode', label: messages('common.currency')/*币种*/, component: 'Selector',
      props: {
        type: 'currency',
        params: { userOId: this.props.loginUser.userOID },
        filter: item => item.enable,
        searchIfKeywordIsNull: true
      },
      dataIndex: 'currencyCode'
    },
    {
      id: 'reimbursementBatchOid', label: messages('finance-1.key505')/*付款批次号*/,
      component: 'Selector',
      props: {
        placeholder: messages('common.please.input')/*请输入*/ + messages('finance-1.key505')/*付款批次号*/,
        selectorData: {
          ...selectorData['user'],
          key: 'reimbursementBatchOID'
        },
        params: {
          batchType: 3001,
          roleType: 'TENANT'
        }
      }
    },
    {
      id: 'selectCompanyOIDs', label: messages('finance-1.key72')/*公司*/, component: 'Chooser',
      props: {
        type: 'permission_company',
        labelKey: 'name',
        valueKey: 'companyOID'
      },
      parser: value => ({ selectCompanyOIDs: value ? value.map(item => item.companyOID) : undefined }),
      tagParser: value => (value.map(item => item.name).join(','))
    },
    {
      id: 'searchCostCenterCommands', label: messages('finance-1.key506')/*成本中心*/,
      component: <CostCenterSearchForm title={messages('finance-1.key506')/*成本中心*/} type='id'/>,
      tagParser: value => messages('common.total.selected',{arg1: value.length})/*已选 {arg1} 条*/
    },
    {
      id: 'realPaymentData', label: messages('finance-1.key507')/*付款日期*/, component: 'DateRangePicker',
      parser: value => ({
        realPaymentStartDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
        realPaymentEndDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
      })
    },
    {
      id: 'lastAuditApprovalId',
      label: messages('finance-1.key508')/*审核人*/,
      component: 'Chooser',
      props: {
        type: 'finance-auditable-users',
        labelKey: 'fullName',
        valueKey: 'id',
        single: true
      },
      parser: value => ({
        lastAuditApprovalId: value && value.length ? value[0].id : undefined
      }),
    }, Partner,
    {
      id: 'deliveryCode', label: messages('finance-1.key34')/*快递单号*/, component: 'Input'
    },
    {
      id: 'batchNumber', label: messages('finance-1.key500')/*批量打印批次号*/,
      component: <SelectBatchNumber entityType={'3001'}/>,
      parser: value => {
        if (!value) {
          return null;
        } else {
          const { existsExpenseReportBatchId, expenseReportBatchId } = value;
          return existsExpenseReportBatchId && !expenseReportBatchId ? null : (
            !existsExpenseReportBatchId ?
              { existsLoanBillBatchId: existsExpenseReportBatchId } :
              { loanBillBatchId: expenseReportBatchId, existsLoanBillBatchId: existsExpenseReportBatchId }
          );
        }
      }
    },
    {
      id: 'status', label: messages('common.column.status')/*状态*/,
      component: (
        <Checkbox.Group>
          {
            this.statusOptions.map(item => <Checkbox key={item.value} value={item.value}>{item.label}</Checkbox>)
          }
        </Checkbox.Group>
      ),
      tagParser: value => this.statusOptions.filter(item => value.find(key => item.value === key)).map(item => item.label).join(','),
      row: true,
      dataIndex: 'status'
    }
  ];

  service = (page, size, searchParams) => {
    const { sort } = this.state;
    if (sort) {
      searchParams.sorts = {
        property: sort.split(',')[0],
        direction: sort.split(',')[1]
      };
    }
    searchParams.partnerId && (searchParams.partnerId = searchParams.partnerId[0]);
    searchParams.entityType = 3001;
    this.setState({ searchParams: { ...searchParams, entityType: 1008 } });
    return financeViewService.getFinanceViewList(page, size, searchParams);
  };

  handleRowClick = record => {
    openSlideFrame.openLoanReport({
      formOID: record.formOID,
      loanBillOID: record.entityOID,
      pathname: this.props.pathname
    }, {
      afterClose: value => {typeof value === 'boolean' && value && this.advancedTableRef.getList()}
    }, this);
  };

  toGenerateExpenseBatch = () => {
    this.setState({ batchBtnLoading: true });
    const { searchParams } = this.state;
    financeViewService.createBatch({ ...searchParams, batchSize: 100 }).then(res => {
      this.setState({ batchBtnLoading: false });
      if (res.data.total) {
        this.setState({ modalVisible: false });
        message.success(messages('finance-1.key509')/*批次生成成功*/);
        this.props.tabChange('download');
      } else {
        message.error(messages('finance-1.key510')/*批次号为空的单据才可生成批次！*/)
      }
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ batchBtnLoading: false })
    })
  };

  render() {
    const { searchParams, batchBtnLoading } = this.state;
    return (
      <div style={{height: '100%'}}>
        <AdvancedTable
          service={this.service}
          index
          title={messages('finance-1.key474')/*借款单查看*/}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          waterMark
          onChange={this.handleSortChange}
          rowKey='entityOID'
          tableName='cash-advance-view'
          columns={this.columns}
          onRef={ref => this.advancedTableRef = ref}
          searchForm={this.searchForm}
          footer={[
            <ExportModal
              type={"btn"}
              btnType="primary"
              style={{display: 'inline-block', marginRight: '10px'}}
              exportTitle={messages('finance-1.key511')/*导出搜索数据*/}
              exportType="BILL_CHECK"
              exportCondition={{
                billCheckSearchCommand: searchParams
              }}
              exportCommand={'EXP_OR_LOANBILL'}
            />,
            <Button
              loading={batchBtnLoading}
              onClick={this.toGenerateExpenseBatch}
            >
              {messages('finance-1.key512')/*生成批次*/}
            </Button>
          ]}
          header={(
            <Alert
              className="notice"
              type="info"
              showIcon
              style={{ marginBottom: '12px' }}
              message={<div
                dangerouslySetInnerHTML={{
                  __html: messages('finance-1.key513')/*列表中<span class='color-blue'>批量打印批次号为空</span>的数据将会生成批次。*/
                }}/>}
            />
          )}
        />
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser
  }
}

export default LoanView
